import configparser
import os
import random
import csv
from flask import Flask, request, jsonify

app = Flask(__name__)

# Set default path for config.ini
default_config_path = os.path.join(app.root_path, 'config.ini')

# Check for an environment variable for a custom config path
config_path = os.environ.get('FLASK_CONFIG_PATH', default_config_path)

# Set up configparser for configuration file
config = configparser.ConfigParser()
config.read(config_path)

# Determine CSV file path, base audio folder path, and get_word mode from config file
csv_file_path = config['Paths']['csv_file']
error_csv_path = config['Paths']['error_csv']  # Add this line
base_audio_folder = config['Paths']['base_audio_folder']
get_word_mode = config['Settings'].get('get_word_mode', 'random')  # Default to 'random' if not set
shuffle_word_first = config['Settings'].get('shuffle_words_first', 'false')  # Default to 'false' if not set

words = []
with open(csv_file_path, 'r') as file:
    reader = csv.reader(file)
    words = list(reader)
if shuffle_word_first.lower() == 'true':
    random.shuffle(words)  # Shuffle words

ignore_idx = []
current_idx = 0  # For sequential mode
max_get_word_try = 5

@app.route('/')
def index():
    return app.send_static_file('index.html')

@app.route('/get_word', methods=['GET'])
def get_word():
    if get_word_mode == 'sequential':
        return get_word_sequential()
    else:
        return get_word_random()

def get_word_sequential():
    global current_idx
    while current_idx < len(words):
        word = words[current_idx]
        word_id = word[0]
        audio_folder = random.choice(["Monica", "Roger", "Guy", "Jenny"])
        audio_file = os.path.join(base_audio_folder, audio_folder, f"{word_id}.wav")
        if os.path.exists(audio_file):
            response = {"index": current_idx, "audio_file": audio_file}
            current_idx += 1
            return jsonify(response)
        else:
            current_idx += 1
    return jsonify({"message": "No more words available"})

def get_word_random():
    global ignore_idx
    global before_idx
    for i in range(max_get_word_try):
        word_index = random.randint(0, len(words) - 1)
        if word_index in ignore_idx or (word_index == before_idx and (len(words) - len(ignore_idx)) > 1):
            continue
        word = words[word_index]
        word_id = word[0]
        audio_folder = random.choice(["Monica", "Roger", "Guy", "Jenny"])
        audio_file = os.path.join(base_audio_folder, audio_folder, f"{word_id}.wav")
        if not os.path.exists(audio_file):
            ignore_idx.append(word_index)
        else:
            before_idx = word_index
            return jsonify({"index": word_index, "audio_file": audio_file})
    return jsonify({"message": "No valid word found"})

@app.route('/get_details', methods=['GET'])
def get_details():
    index = int(request.args.get('index', 0))
    word_details = words[index][1:]
    return jsonify({"details": word_details})

@app.route('/check_word', methods=['POST'])
def check_word():
    index = int(request.json['index'])
    user_input = request.json['user_input']
    if user_input.lower() == words[index][1].lower():
        return jsonify({"result": "Correct!"})
    else:
        with open(error_csv_path, 'a', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(words[index])
        return jsonify({"result": "Incorrect!"})
    
@app.route('/reset', methods=['POST'])
def reset():
    global current_idx
    current_idx = 0
    return jsonify({"message": "Index reset to 0"})


if __name__ == '__main__':
    app.run(debug=True)
